from django.shortcuts import render

# Create your views here.


import time
from datetime import datetime


from django.http import JsonResponse
from rest_framework.views import APIView

import basic
from basic.models import ProcessNumber
from utils.binance import Binance
from binance_era.settings import Parameter as era_parameter
from utils.timestamp import time_stamp_date, now_time_stamp


class HomeData(APIView):
    """
    数据首页接口
    """

    def get(self, request):

        try:
            binance = Binance(parameter=era_parameter, strategy=basic.Strategy.era)
        except:
            return JsonResponse({'code': 31400, 'msg': '操作请求体错误.'})

        # binance.logger_error(f"邮件测试!!!")

        process_obj = ProcessNumber.objects.filter(exchange=binance.exchange_name,
                                                   strategy=binance.strategy_name).first()
        cache = binance.cache_get(binance.parameter.db_coll)

        # 计算运行天数
        start_time = int(cache[binance.parameter.db_coll_timeStamp] / 1000)
        end_time = int(now_time_stamp() / 1000)
        run_days = (datetime.fromtimestamp(end_time) - datetime.fromtimestamp(start_time)).days

        # echart数据
        chart_list = binance.cache_get(binance.parameter.db_coll_up)
        if not chart_list:
            chart_list = [0]

        data = {
            "head": [
                {"type": "交易所可用余额", "text": f"{binance.exchange_available_balance()}U"},
                {"type": "启动模式", "text": "实盘" if process_obj.pan_opening == '0' else "模拟盘"},
                {"type": "平仓停止", "text": "启用中" if process_obj.status == '0' else "未启用"},
                {"type": "本地钱包余额", "text": f"{round(cache[binance.parameter.db_coll], 2)}U"},
                {"type": "本地初始金额", "text": f"{round(cache[binance.parameter.db_coll_init], 2)}U"},
                {"type": "运行", "text": f"{run_days}天"},
            ],  # 上部数据
            "uchart_option": {
                "opts": {"xAxis": {"boundaryGap": "justify"}},
                "option": {
                    "categories": [i for i in range(len(chart_list))],
                    "series": [{"name": "本地资金账户曲线", "data": chart_list}]
                }
            }
        }
        return JsonResponse({'data': data, 'code': 200, 'msg': 'ok'})


class MineArgument(APIView):
    """
    我的页面：程序参数
    """

    def get(self, request):

        try:
            binance = Binance(parameter=era_parameter, strategy=basic.Strategy.era)
        except:
            return JsonResponse({'code': 31400, 'msg': '操作请求体错误.'})

        data = dict()
        data["symbol"] = binance.parameter.set_inst     # 交易货币
        data["balance"] = binance.exchange_available_balance()  # 交易所可用余额
        data["init_balance"] = self.get_init_balance(binance)  # 初始金额
        data["min_balance"] = binance.parameter.set_balance  # 程序启动最低余额
        data["ccy"] = binance.parameter.ccy  # 计价货币
        data["commission"] = f"{binance.parameter.commission * 100}%"  # 手续费
        data["isolated"] = "逐仓" if binance.parameter.isolated == "ISOLATED" else "全仓"  # 持仓模式
        data["threshold"] = f"{binance.parameter.set_min_balance * 100}%"  # 账户阀值(低于时退出程序)
        data["min_margin"] = f"{binance.parameter.set_margin}%"  # 最低保证金

        return JsonResponse({'data': data, 'code': 200, 'msg': 'ok'})

    @staticmethod
    def get_init_balance(binance):
        """ 初始金额 """
        data = binance.cache_get(binance.parameter.db_coll)
        if data:
            return data[binance.parameter.db_coll_init]
        return None

